package com.echo.im.client.handler.suport.platform;

import com.echo.im.client.handler.suport.AbstractPlatformMessageHandler;
import com.echo.im.client.status.OnlineStatusService;
import com.echo.im.common.enums.IMCmdType;
import com.echo.im.common.model.info.IMRecvInfo;
import com.echo.im.common.model.message.platform.UserLogoutMessage;
import com.echo.im.infrastructure.mq.event.model.push.PushMessageEvent;
import com.echo.im.infrastructure.mq.event.producer.EventPublisher;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author: echo
 * @time: 2024-08-16
 */

@Slf4j
@Component
@RequiredArgsConstructor
public class UserLogoutMessageHandler extends AbstractPlatformMessageHandler<UserLogoutMessage> {

    private final EventPublisher eventPublisher;
    private final PushMessageEvent pushMessageEvent;
    private final OnlineStatusService onlineStatusService;

    @Override
    public void sendPlatformCmd(UserLogoutMessage userLogoutCmd) {
        log.info("Sending platform command: {}", userLogoutCmd);
        Map<Integer, List<Integer>> serverIdTerminalListMap = onlineStatusService.getServerIdTerminalListMap(userLogoutCmd.getUserId(), userLogoutCmd.getTerminalList());
        serverIdTerminalListMap.forEach(
                (serverId, terminalList) -> {
                    IMRecvInfo<UserLogoutMessage> recvInfo = new IMRecvInfo<>();
                    UserLogoutMessage newUserLogoutCmd = new UserLogoutMessage(userLogoutCmd.getUserId(), terminalList);
                    recvInfo.setData(newUserLogoutCmd);
                    recvInfo.setCmd(IMCmdType.PLATFORM_MESSAGE.code());
                    eventPublisher.publishWithServerId(pushMessageEvent,recvInfo,serverId.toString());
                }
        );
    }

}
